﻿
using B.S.BasicData.Api.Read.Applications.Command;
using B.S.BasicData.Api.Read.Dto;
using B.S.BasicData.Domains;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructures;
using MediatR;

namespace B.S.BasicData.Api.Read.Applications.CommandHandler
{
    public class UserRoleQueryCommandHandler : IRequestHandler<UserRoleQueryCommand, ApiResult<ApiPaging<UserRole>>>
    {
        private readonly IBaseRepository<Role> roleRepository;
        private readonly IBaseRepository<UserInfos> userRepository;
        private readonly IBaseRepository<RoleUser> roleuserRepository;

        public UserRoleQueryCommandHandler(IBaseRepository<Role> roleRepository, IBaseRepository<UserInfos> userRepository, IBaseRepository<RoleUser> roleuserRepository)
        {
            this.roleRepository = roleRepository;
            this.userRepository = userRepository;
            this.roleuserRepository = roleuserRepository;
        }

        public Task<ApiResult<ApiPaging<UserRole>>> Handle(UserRoleQueryCommand request, CancellationToken cancellationToken)
        {
            ApiResult<ApiPaging<UserRole>> result = new ApiResult<ApiPaging<UserRole>>();
            result.Code = ApiEnum.Success;
            result.Message = "用户角色列表展示成功";
            var list = from a in roleRepository.GetAll()
                       join b in roleuserRepository.GetAll() on a.RoleId equals b.RoleId
                       join c in userRepository.GetAll() on  b.UserId equals c.UserId

                       select new UserRole
                       {
                           RoleId = a.RoleId,
                           RoleName = a.RoleName,
                           CreateTime= a.CreateTime,
                           UserName=c.UserName,
                           NickName=c.NickName,
                           Password=c.Password,
                           State=a.State,
                           UserId=c.UserId
                           
                       };
            //进不去
             if(!string.IsNullOrEmpty(request.UserName))
            {
                list = list.Where(x => x.UserName == request.UserName);

            }
             var TotalCount=list.Count();
            var TotalPage = (int)Math.Ceiling((TotalCount * 1.0) / request.PageSize);
            list = list.OrderByDescending(x => x.UserId).Skip((request.PageIdenx - 1) * request.PageSize).Take(request.PageSize);
            ApiPaging<UserRole> apiPaging = new ApiPaging<UserRole>();
            apiPaging.TotalCount = TotalCount;
            apiPaging.TotalPage = TotalPage;
            apiPaging.data = list.ToList();
            result.data = apiPaging;
            return Task.FromResult(result);
        }
    }
}
